package com.ylbh.modules.returngoods.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylbh.common.pojo.goodsorder.dto.OrderShipmentDTO;
import com.ylbh.common.pojo.goodsorder.vo.ExpressCompanyVO;
import com.ylbh.common.pojo.home.vo.HomeStateStatisticsVO;
import com.ylbh.common.pojo.returngoods.UserMailDTO;
import com.ylbh.common.pojo.returngoods.dto.ExecutionPaymentDTO;
import com.ylbh.common.pojo.returngoods.dto.OrderReturnToExamineDTO;
import com.ylbh.common.pojo.returngoods.dto.ShoppingMallOrderReturnListDTO;
import com.ylbh.common.pojo.returngoods.dto.UpdateOrderReturnDetailsDTO;
import com.ylbh.common.pojo.returngoods.vo.*;
import com.ylbh.common.utils.HttpClientHelperUtils;
import com.ylbh.common.utils.ShiroUtils;
import com.ylbh.modules.returngoods.entity.ShoppingOrderReturn;
import com.ylbh.modules.returngoods.mapper.ShoppingOrderReturnMapper;
import com.ylbh.modules.returngoods.service.ShoppingOrderReturnService;
import com.ylbh.modules.shopping_orderform.dao.ShoppingOrderformDao;
import com.ylbh.modules.shopping_orderform.entity.ShoppingOrderformEntity;
import com.ylbh.modules.shopping_orderform.entity.entityVo.ShoppingOrderformReturnVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.utils.PageUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;

/**
 * 退货
 * @author czx
 * @date 2019-06-09 14:22:40
 */
@Service("shoppingOrderReturnService")
public class ShoppingOrderReturnServiceImpl extends ServiceImpl<ShoppingOrderReturnMapper, ShoppingOrderReturn> implements ShoppingOrderReturnService {

    @Autowired
    private ShoppingOrderReturnMapper shoppingOrderReturnMapper;

    @Autowired
    private ShoppingOrderformDao shoppingOrderformDao;

    // 微信回调地址
    @Value("${url.wxCallback}")
    private String wxCallback;

    // 支付宝回调地址
    @Value("${url.aliCallback}")
    private String aliCallback;

    // 退款接口地址
    @Value("${url.refundUrl}")
    private String refundUrl;

    // 审核接口地址
    @Value("${url.returnAudit}")
    private String returnAudit;

    // 发货接口地址
    @Value("${url.shipmentByExchange}")
    private String shipmentByExchange;

    // 核销
    @Value("${url.writeOff}")
    private String writeOff;

    @Value("${url.vendorConfirmation}")
    private String vendorConfirmation;

    /**
     * 商城订单退货列表
     * @param orderReturnListDTO
     * @return
     */
    @Override
    public PageUtils queryShoppingMallOrderReturnList(ShoppingMallOrderReturnListDTO orderReturnListDTO) throws ExecutionException, InterruptedException {
        Page<Object> page = new Page<>(orderReturnListDTO.getPage(), orderReturnListDTO.getLimit());
        List<ShoppingMallOrderReturnListVO> list = shoppingOrderReturnMapper.selectShoppingMallOrderReturnList(orderReturnListDTO, page);
        final CountDownLatch countDownLatch = new CountDownLatch(list.size());
        ExecutorService es = Executors.newFixedThreadPool(list.size());
        for (final ShoppingMallOrderReturnListVO vo : list) {
            Future<String> future = es.submit(() -> {
                try {
                    if (!StringUtils.isEmpty(vo.getOrderNo())) {
                        ShoppingOrderformReturnVo SoeVo =shoppingOrderformDao.selectByOrderId(vo.getOrderNo());
                        if (null != SoeVo) {
                            vo.setDeliveryAddress(SoeVo.getDeliveryAddress());
                            vo.setGoodsAmount(SoeVo.getGoodsAmount());
                        }
                    }
                    if (!StringUtils.isEmpty(vo.getDeliveryAddress())) {
                        String[] address = vo.getDeliveryAddress().split(",,,,,,");
                        if (address.length == 3) {
                            vo.setIphone(address[1]);
                            vo.setPayUserName(address[0]);
                        }
                    }
                    if (!StringUtils.isEmpty(vo.getGoodsCartId())) {
                        String[] goodsCarts = vo.getGoodsCartId().split(",");
                        List list1 = new ArrayList<SonOrderReturnVO>();
                        List<String> cardIds = Arrays.asList(goodsCarts);
                        for (String id : cardIds) {
                            SonOrderReturnVO son = shoppingOrderReturnMapper.selectSonOrder(id,vo.getReturnId());
                            if (null != son)
                                list1.add(son);
                        }
                        vo.setSonOrder(list1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
                return Thread.currentThread().getName();
            });
            System.out.println(future.get());
        }
        try {
            es.shutdown();
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new PageUtils(new Page<ShoppingMallOrderReturnListVO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 对退货/退款/换货订单进行审核操作
     * @param returnId
     * @param type
     * @param remark
     */
    @Override
    public void modifyReturnStatusById(String returnId, String type,String goodsCartId, String remark) {
        shoppingOrderReturnMapper.updateReturnStatusById(returnId, type, remark, ShiroUtils.getUserId(), new Date());
        // 修改子订单表中子订单的信息
        if (StringUtils.isNotBlank(goodsCartId)) {
            String[] cartId = goodsCartId.split(",");
            shoppingOrderReturnMapper.updateGoodsCartById(Arrays.asList(cartId), type);
        }
    }

    /**
     * 商城订单退货列表详情
     * @param returnId
     * @return
     */
    @Override
    public ShoppingMallOrderReturnDetailsVO getShoppingMallOrderReturnDetails(String returnId) {
        ShoppingMallOrderReturnDetailsVO details = shoppingOrderReturnMapper.selectShoppingMallOrderReturnDetails(returnId);
        BigDecimal sumMoney = new BigDecimal("0");
        if (StringUtils.isNotBlank(details.getGoodsCartId())){
            String[] cardId = details.getGoodsCartId().split(",");
            if (cardId.length > 0){
                ArrayList<OrderReturnGoodsVO> list = new ArrayList<>();
                for (String id : cardId) {
                    // 查询子订单商品信息
                    OrderReturnGoodsVO cart = shoppingOrderReturnMapper.selectGoodsCart(id);
                    ReturnMoneyVO vo = shoppingOrderReturnMapper.selectReturnMoney(id);
                    if (vo.getPriceType() == 2) {
                        sumMoney = sumMoney.add(vo.getPrice().multiply(new BigDecimal(vo.getCount())).add(vo.getShipPrice()));
                    } else {
                        sumMoney = sumMoney.add(vo.getShipPrice());
                    }
                    list.add(cart);
                }
                details.setList(list);
            }
            details.setSumMoney(sumMoney);
        }
        // 根据退换货的申请图片，进行切割
        if (StringUtils.isNotBlank(details.getApplyReturnImages())) {
            ArrayList<String> list = new ArrayList<>();
            String[] image = details.getApplyReturnImages().split(",");
            for (String IMG : image) {
                list.add(IMG);
            }
            details.setImg(list);
        }
        return details;
    }

    /**
     * 对退货状态进行审核操作
     * @param orderReturnToExamineDTO
     * @return
     */
    @Override
    public String modifyReturnToExamine(OrderReturnToExamineDTO orderReturnToExamineDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("returnId", orderReturnToExamineDTO.getReturnId());
        map.put("goodsCardId", orderReturnToExamineDTO.getGoodsCartId());
        map.put("returnStatus", orderReturnToExamineDTO.getReturnStatus());
        map.put("userAuditRemark", orderReturnToExamineDTO.getUserAuditRemark());
        map.put("platformAuditRemark", orderReturnToExamineDTO.getSupplierDeliveryName() + "  " +
                                       orderReturnToExamineDTO.getSupplierDeliveryIphone() + "  " +
                                       orderReturnToExamineDTO.getSupplierDeliveryAddress() + "  (" +
                                       orderReturnToExamineDTO.getSupplierDeliveryRemark() + ")");
        map.put("supplierDeliveryName", orderReturnToExamineDTO.getSupplierDeliveryName());
        map.put("supplierDeliveryIphone", orderReturnToExamineDTO.getSupplierDeliveryIphone());
        map.put("supplierDeliveryAddress", orderReturnToExamineDTO.getSupplierDeliveryAddress());
        map.put("supplierDeliveryRemark", orderReturnToExamineDTO.getSupplierDeliveryRemark());
        map.put("supplierShipCode", orderReturnToExamineDTO.getSupplierShipCode());
        map.put("supplierShipId", orderReturnToExamineDTO.getSupplierShipId());
        map.put("supplierShipRemark", orderReturnToExamineDTO.getSupplierShipRemark());
        map.put("updateUserId", orderReturnToExamineDTO.getUpdateUserId().toString());
        return HttpClientHelperUtils.sendHttpPost(returnAudit, map);
    }

    @Override
    public List<ExpressCompanyVo> queryExpress() {
        return shoppingOrderReturnMapper.selectExpress();
    }

    /**
     * 对退换货进行发货操作
     * @param orderReturnToExamineDTO
     * @return
     */
    @Override
    public String shipmentByExchange(OrderReturnToExamineDTO orderReturnToExamineDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("returnId", orderReturnToExamineDTO.getReturnId());
        map.put("goodsCardId", orderReturnToExamineDTO.getGoodsCartId());
        map.put("returnStatus", orderReturnToExamineDTO.getReturnStatus());
        map.put("userAuditRemark", orderReturnToExamineDTO.getUserAuditRemark());
        map.put("platformAuditRemark", orderReturnToExamineDTO.getPlatformAuditRemark());
        map.put("supplierDeliveryName", orderReturnToExamineDTO.getSupplierDeliveryName());
        map.put("supplierDeliveryIphone", orderReturnToExamineDTO.getSupplierDeliveryIphone());
        map.put("supplierDeliveryAddress", orderReturnToExamineDTO.getSupplierDeliveryAddress());
        map.put("supplierDeliveryRemark", orderReturnToExamineDTO.getSupplierDeliveryRemark());
        map.put("supplierShipCode", orderReturnToExamineDTO.getSupplierShipCode());
        map.put("supplierShipId", orderReturnToExamineDTO.getSupplierShipId());
        map.put("supplierShipRemark", orderReturnToExamineDTO.getSupplierShipRemark());
        map.put("updateUserId", orderReturnToExamineDTO.getUpdateUserId().toString());
        return HttpClientHelperUtils.sendHttpPost(shipmentByExchange, map);
    }

    /**
     * 修改供应商是否打款给公司
     * @param returnId
     * @param type
     */
    @Override
    public void modifyMakeMoneyType(String returnId, String type) {
        shoppingOrderReturnMapper.updateMakeMoneyType(returnId, type, new Date());
    }

    /**
     * 立即执行退款
     * @param executionPaymentDTO
     * @return
     */
    @Override
    public String executionPayment(ExecutionPaymentDTO executionPaymentDTO) {
        if (StringUtils.isNotBlank(executionPaymentDTO.getOrderNo())) {
            // 查询商城订单表中的支付方式和流水号
            RefundOrderFormVO vo = shoppingOrderReturnMapper.selectOrderForm(executionPaymentDTO.getOrderNo());
            HashMap<String, String> map = new HashMap<>();
            map.put("tradeId", vo.getOutOrderId());
            map.put("orderNo", executionPaymentDTO.getOrderNo());
            map.put("returnId", executionPaymentDTO.getReturnId());
            map.put("totalMoney", executionPaymentDTO.getTotalMoney().toString());
            map.put("refundMoney", executionPaymentDTO.getRefundMoney().toString());
            map.put("retrunSrc", "0");
            if (StringUtils.isNotBlank(vo.getPaymentId())) {
                // 微信
                if ("20".equals(vo.getPaymentId())) {
                    map.put("returnMoneyType", "0");
                    map.put("notifyUrl", wxCallback);
                }
                // 支付宝
                if ("17".equals(vo.getPaymentId())) {
                    map.put("returnMoneyType", "1");
                    map.put("notifyUrl", aliCallback);
                }
            }
            map.put("refundReason", executionPaymentDTO.getRefundReason());
            return HttpClientHelperUtils.sendHttpPost(refundUrl, map);
        }
        return null;
    }

    /**
     * 查询退款用户的退款总金额
     * @param returnId
     * @return
     */
    @Override
    public RefundAmountVO getRefundAmount(String returnId) {
        return shoppingOrderReturnMapper.selectRefundAmount(returnId);
    }

    /**
     * 根据当前类型来修改物流号
     * @param type
     * @param orderShipmentDTO
     */
    @Override
    public void modifyLogisticsInformation(Integer type, OrderShipmentDTO orderShipmentDTO) {
        orderShipmentDTO.setDate(new Date());
        shoppingOrderReturnMapper.updateLogisticsInformation(type, orderShipmentDTO);
    }

    /**
     * 供应商确认收货
     * @param returnId
     */
    @Override
    public String modifyVendorConfirmation(String returnId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("returnId", returnId);
        map.put("goodsCardId", "");
        map.put("returnStatus", "");
        map.put("userAuditRemark", "");
        map.put("platformAuditRemark", "");
        map.put("supplierDeliveryName", "");
        map.put("supplierDeliveryIphone", "");
        map.put("supplierDeliveryAddress", "");
        map.put("supplierDeliveryRemark", "");
        map.put("supplierShipCode", "");
        map.put("supplierShipId", "");
        map.put("supplierShipRemark", "");
        map.put("updateUserId", ShiroUtils.getUserId().toString());
        return HttpClientHelperUtils.sendHttpPost(vendorConfirmation, map);
//        shoppingOrderReturnMapper.updateVendorConfirmation(returnId, ShiroUtils.getUserId(), new Date());
    }

    /**
     * 换货订单-供应商发货
     * @param orderShipmentDTO
     */
    @Override
    public void modifySupplierDelivery(OrderShipmentDTO orderShipmentDTO) {
        orderShipmentDTO.setDate(new Date());
        shoppingOrderReturnMapper.updateSupplierDelivery(orderShipmentDTO, ShiroUtils.getUserId());
    }

    /**
     * 退换货核销
     * @param returnId
     * @return
     */
    @Override
    public String writeOffByReturnId(String returnId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("updateUserId", ShiroUtils.getUserId().toString());
        map.put("returnId", returnId);
        map.put("goodsCartId", "");
        map.put("returnStatus", "");
        map.put("userAuditRemark", "");
        map.put("platformAuditRemark", "");
        map.put("supplierDeliveryName", "");
        map.put("supplierDeliveryIphone", "");
        map.put("supplierDeliveryAddress", "");
        map.put("supplierDeliveryRemark", "");
        map.put("supplierShipCode", "");
        map.put("supplierShipId", "");
        map.put("supplierShipRemark", "");
        return HttpClientHelperUtils.sendHttpPost(writeOff, map);
    }

    /**
     * 供应商确认收货
     * @param orderReturnToExamineDTO
     * @return
     */
    @Override
    public String vendorConfirmation(OrderReturnToExamineDTO orderReturnToExamineDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("returnId", orderReturnToExamineDTO.getReturnId());
        map.put("goodsCardId", orderReturnToExamineDTO.getGoodsCartId());
        map.put("returnStatus", orderReturnToExamineDTO.getReturnStatus());
        map.put("userAuditRemark", orderReturnToExamineDTO.getUserAuditRemark());
        map.put("platformAuditRemark", orderReturnToExamineDTO.getPlatformAuditRemark());
        map.put("supplierDeliveryName", orderReturnToExamineDTO.getSupplierDeliveryName());
        map.put("supplierDeliveryIphone", orderReturnToExamineDTO.getSupplierDeliveryIphone());
        map.put("supplierDeliveryAddress", orderReturnToExamineDTO.getSupplierDeliveryAddress());
        map.put("supplierDeliveryRemark", orderReturnToExamineDTO.getSupplierDeliveryRemark());
        map.put("supplierShipCode", orderReturnToExamineDTO.getSupplierShipCode());
        map.put("supplierShipId", orderReturnToExamineDTO.getSupplierShipId());
        map.put("supplierShipRemark", orderReturnToExamineDTO.getSupplierShipRemark());
        map.put("updateUserId", orderReturnToExamineDTO.getUpdateUserId().toString());
        return HttpClientHelperUtils.sendHttpPost(vendorConfirmation, map);
    }

    /**
     * 修改退换货详情信息
     * @param dto
     */
    @Override
    public void modifyReturnGoodsById(UpdateOrderReturnDetailsDTO dto) {
        shoppingOrderReturnMapper.updateReturnGoodsById(dto);
    }

    /**
     * 退换货未审核订单开始
     * @return
     */
    @Override
    public List<HomeStateStatisticsVO> queryOrderReturn() {
        return shoppingOrderReturnMapper.selectOrderReturn();
    }

    /**
     * 替用户进行寄件操作
     * @param userMailDTO
     * @return
     */
    @Override
    public void modifyUserMailById(UserMailDTO userMailDTO) {
        // 先查询这个订单号是否是售后订单，并且审核已经通过
        int returnStatus = shoppingOrderReturnMapper.selectIsAfterSalesOrders(userMailDTO.getReturnId());
        if (returnStatus == 2) {
            Integer expressId = shoppingOrderReturnMapper.selectExpressByName(userMailDTO.getCompanyName());
            userMailDTO.setCompanyId(expressId);
            // 则对这笔订单进行替用户寄件，并将状态修改为3，用户是否寄件状态改成1，和插入物流信息
            shoppingOrderReturnMapper.updateMailingById(userMailDTO, new Date(), ShiroUtils.getUserId());
        }
    }
}
